<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Purchase_m extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
	
	function save()
	{
		$pid = $this->input->post('pid');
		//重新计算金额
		$price = $this->input->post('price');
		$nums  = $this->input->post('nums');
		$total = $this->input->post('total');
		for($x=0;$x<count($price);$x++){
			if($price[$x]==""){
				$price[$x] = 0;
			}
			if($total[$x]==""){
				$total[$x] = 0;
			}
			if($nums[$x]==""){
				$nums[$x] = 0;
			}
			$total[$x] = $price[$x] * $nums[$x];
			$goodsprice += $total[$x];
		}
		$post="";
		
		
		$post['opertime'] = date("Y-m-d H:i:s");
		$post['othermoney'] = $this->input->post('othermoney');
		$post['goodsprice'] = $goodsprice;
		$post['takeprice']  = $this->input->post('takeprice');
		$post['othermoney'] = $this->input->post('othermoney');
		$post['allmoney']   = $this->input->post('allmoney');
        $post['made_factory']   = $this->input->post('made_factory');
		if(trim($post['made_factory'])==3){
			$post['made_way'] = trim($this->input->post("made_way")); //外采购，采购途径 1、taobao 2、1688 99、其他
		}
		 $good_no = $this->input->post('good_no');
		 $cangs = $this->getcang($good_no);
		$post['cang']		= $cangs?$cangs:$this->input->post('tostock');
		$post['daysum']   = $this->input->post('daysum');
		$post['tb_ordersn']   = $this->input->post('platform_message');
		if(trim($this->input->post('ordersn'))){
			$post['ordersn']   = trim($this->input->post('ordersn'));
		}

		$post['chkflag']  = 0;
		$post['status']   =1;
		
	

		$post['memo']  = $this->input->post('memo');
		$change_purchase = "";
		$this->db->trans_begin();
		if($pid>0)
		{
			$upd_flag = 1;
			$row_purchase_list = $this->fun->getdatabasesdetail('db_purchase_list', " AND id = '" . $pid ."'");
			if($post['cang'] != $row_purchase_list['cang']){
				$change_purchase.= "发往仓库由:".$row_purchase_list['cang']."号仓,更改为:".$post['cang']."号仓<br/>";
			}
			$orderstockid =  $row_purchase_list['orderstockid'];
			
			
			$this->db->update('db_purchase_list',$post,'id ='.$pid);
			$newpid = $pid;
		}else{
			$post['ps']   =1;
			$post['orderstockid'] = $this->getNo();
			$orderstockid =  $post['orderstockid'];
			$post['oper'] = $_COOKIE["userid"];
			$post['createuser'] = $_COOKIE["username"];
			$this->db->insert('db_purchase_list',$post);
			$pid = $this->db->insert_id();
			$newpid = 0;
			$upd_flag = 0;
			
			$made_factory = intval($this->input->post('made_factory'));
			if($made_factory==4 || $made_factory==5 || $made_factory==6)
			{
				$this->db->update('db_purchase_list',array("orderstockid"=>$pid,"tb_ordersn"=>$pid),'id ='.$pid);
			}else{
				$this->db->update('db_purchase_list',array("orderstockid"=>$pid),'id ='.$pid);
			}
			
			//添加日志信息
			$msg = "成功生成采购单";
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			//$arr_logs['pid'] = "";
			$arr_logs['goods_code'] = $post['orderstockid'];
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $pid;
			$this->db->insert('db_externalbuy_log', $arr_logs);

		}
		
		//存商品
		$good_name = $this->input->post('good_namec');
		$good_no = $this->input->post('good_no');
		$goods_id =$this->input->post('goods_id');
		$buyer =$this->input->post('buyer');
		$price = $this->input->post('price');
		$nums = $this->input->post('nums');
		$total = $this->input->post('total');

		$skucode = $this->input->post('skucode');
		$skumemo = $this->input->post('skumemo');

		$arr_unique = array();

		$db_goods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $goods_id[0] ."'");
		$goods_parent_sku = trim($db_goods['goods_parent_sku']);
		for($x=0;$x<count($goods_id);$x++){
			//判断
			$goods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $goods_id[$x] ."'");
			$parent_sku = trim($goods['goods_parent_sku']);
			if($parent_sku != $goods_parent_sku){
				//echo "存在不同主SKU商品,请确认后，重新提交!";exit;
			}

			$sell="";
			$sell['good_name'] = $good_name[$x];
			$sell['good_no'] = $good_no[$x];
			$sell['goods_id'] = $goods_id[$x];
			$sell['buyer'] = $buyer[$x];
			$sell['price'] = $price[$x];
			$sell['nums'] = $nums[$x];
			$sell['total'] = $price[$x]*$nums[$x];
			//$sell['total'] = $total[$x];
			$sell['pid'] = $pid;

			$sell['skucode'] = $skucode[$x];
			$sell['skumemo'] = $skumemo[$x];

			//合并具有相同goods_id的商品
			if(!isset($arr_unique[$goods_id[$x]])){
				//$arr_unique[$goods_id[$x]]['good_name'] = $good_name[$x];
				//$arr_unique[$goods_id[$x]]['good_no'] = $good_no[$x];
				//$arr_unique[$goods_id[$x]]['buyer'] = $buyer[$x];
				//$arr_unique[$goods_id[$x]]['price'] = $price[$x];
				$arr_unique[$goods_id[$x]]['nums'] = $nums[$x];
				//$arr_unique[$goods_id[$x]]['total'] = $total[$x];
				//$arr_unique[$goods_id[$x]]['pid'] = $pid;
			}else{
				$arr_unique[$goods_id[$x]]['nums']+=$nums[$x];
			}

			$rsdb = $this->fun->getdatabasesdetail('db_purchase_vice', " AND goods_id = '" .$sell['goods_id'] . "' AND pid='".$pid."'");
			if($rsdb)
			{
				$this->db->update('db_purchase_vice',$sell,"id='".$rsdb['id']."'");
				//echo $this->db->last_query();exit;
				if($upd_flag==1){
					if($rsdb['price']!=$sell['price']){
						$change_purchase.="商品SKU：".$sell['good_no'];
						$change_purchase.= ",采购价由：".$rsdb['price'].",更改为：".$sell['price'];

						//若为外采购商品,则更新外采购商品的成本价，并添加一条日志信息
						if($goods['g_supplier']==3){
							//更新商品日志记录
							$goodslog="";
							$goodslog["goods_id"] = $sell['goods_id'];	//更新商品表 日志信息
							$goodslog["updatetime"] = date("Y-m-d H:i:s");
							$goodslog["createUid"] = $_COOKIE['userid'];
							$goodslog["types"] = 1;
							$goodslog["content"] = "添加采购单,商品SKU：".$sell['good_no'].",商品成本价由：".$rsdb['price'].",更改为：".$sell['price'];
							$goodslog["createUser"] =$_COOKIE['username'];
							$this->db->insert('db_goods_log', $goodslog);

							//修改 外采购商品的成本价
							$this->db->update("db_goods",array("g_costprice"=>$sell['price'])," goods_id ='".$sell['goods_id']."'");

						}



					}
					if($rsdb['nums']!=$sell['nums']){
						if($rsdb['price']==$sell['price']){
							$change_purchase.="商品SKU：".$sell['good_no'];
							$change_purchase.= ",数量由：".$rsdb['nums'].",更改为：".$sell['nums'];
						}else{
							$change_purchase.= ",数量由：".$rsdb['nums'].",更改为：".$sell['nums'];
						}

					}

				}

			}else{
				$this->db->insert('db_purchase_vice',$sell);
				//$cur_insert_id = $this->db->insert_id();


				//若为外采购商品,则需要判断当前的价格，是否与给定的成本价格相同
				if($goods['g_supplier']==3){
					$cur_costprice = $this->fun->get_Goods_costprice($sell['good_no']);
					if($cur_costprice != $sell['price'] && $sell['price'] >0){
						//更新商品日志记录
						$goodslog="";
						$goodslog["goods_id"] = $sell['goods_id'];	//更新商品表 日志信息
						$goodslog["updatetime"] = date("Y-m-d H:i:s");
						$goodslog["createUid"] = $_COOKIE['userid'];
						$goodslog["types"] = 1;
						$goodslog["content"] = "添加采购单,商品SKU：".$sell['good_no'].",商品成本价由：".$rsdb['price'].",更改为：".$sell['price'];
						$goodslog["createUser"] =$_COOKIE['username'];
						$this->db->insert('db_goods_log', $goodslog);

						//修改 外采购商品的成本价
						$this->db->update("db_goods",array("g_costprice"=>$sell['price'])," goods_id ='".$sell['goods_id']."'");

					}

				}

				if($upd_flag==1){
						$change_purchase.="添加SKU：".$sell['good_no'];
						$change_purchase.= ",采购价：".$sell['price'];
						$change_purchase.= ",数量：".$sell['nums'];
						$change_purchase.= "<br/>";
				}
			}
		}
		if($upd_flag==1&&$change_purchase){
			$msg = $change_purchase;
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			$arr_logs['goods_code'] = $row_purchase_list['orderstockid'];
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $pid;
			$this->db->insert('db_externalbuy_log', $arr_logs);
		}

		//若符合条件，更新批量订单列表
		$db_mastergoods = $this->fun->getdatabasesdetail('db_goods', " AND goods_sku = '" . $goods_parent_sku ."'");
		if(count($db_mastergoods)>0){
			$db_goods = $db_mastergoods;
		}

		//若工厂批量订单存在，则作废该工厂批量订单
		if($upd_flag==1){ //修改
			$batchorder_id = $row_purchase_list['tb_ordersn'];
			$batchorder_sql = "SELECT * FROM db_batchorder WHERE order_id = '{$batchorder_id}' AND status != 3 ";
			$batchorder_rs  = $this->db->query($batchorder_sql)->row_array();
			if(count($batchorder_rs)>0){ //若之前存在订单，则作废
				$this->db->update("db_batchorder",array("status"=>3)," order_id = '".$batchorder_id."'");
			}
		}

		if($post['made_factory']==1 || $post['made_factory']==2) {

			if (strlen($goods_parent_sku) == 8) {
				$factory_flag = substr($goods_parent_sku, 0, 2);
				if ($factory_flag == "11" || $factory_flag == "12") {
					$datetime = date("Y-m-d H:i:s");
					//更新 db_batchorder
					$arr_batchorder = array();
					$arr_batchorder['goods_code'] = $db_goods['goods_parent_sku'];
					$arr_batchorder['goods_name'] = $db_goods['goods_name'];
					//$arr_batchorder['price'] = $price[0];
					$arr_batchorder['price'] = $db_goods['wages']; //使用工价
					//工厂预期交货日期
					$timestamp = $post['daysum']*86400+ strtotime($post['opertime']);
					//$arr_batchorder['factory_goods_day'] = date("Y-m-d",$timestamp);
					$arr_batchorder['goods_date'] = date("Y-m-d",$timestamp); //客户期望交货日期

					$arr_batchorder['status'] = 4; //新订单
					if ($post['cang'] == 1) {
						$arr_batchorder['cang'] = "1号仓"; //发往仓库
					}
					if ($post['cang'] == 2) {
						$arr_batchorder['cang'] = "2号仓"; //发往仓库
					}
					$arr_batchorder['createtime'] = $datetime;
					$arr_batchorder['userid'] = $_COOKIE['userid'];
					$arr_batchorder['create_user'] = $_COOKIE['username'];
					if ($factory_flag == "11") {
						$arr_batchorder['factory_id'] = 1; //工厂一
					}
					if ($factory_flag == "12") {
						$arr_batchorder['factory_id'] = 2; //工厂二
					}
					$arr_batchorder['memo'] = $post['memo'];

					$this->db->insert("db_batchorder", $arr_batchorder);
					$order_id = $this->db->insert_id();

					//更新 采购编号
					$this->db->update('db_purchase_list', array('tb_ordersn' => $order_id), " id=" . $pid);

					//更新 db_batchorder_list
					foreach ($arr_unique as $k => $v) {
						$arr_goods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $k . "'");

						$rgoodstype = $this->db->get_one("SELECT GROUP_CONCAT(attr_value ORDER BY attr_id ASC)  AS sta FROM `db_goods_attr` WHERE `goods_id` = '" . $k . "'");
						$arr_conn = explode(",", $rgoodstype['sta']);
						if (!empty($arr_conn[1])) {
							if (mb_substr($arr_conn[0], 0, 1) == "男" || mb_substr($arr_conn[0], 0, 1) == "女") {
								$product_type = $arr_conn[1] . "," . $arr_conn[2] . "," . mb_substr($arr_conn[0], 0, 1);
							} else {
								$product_type = $arr_conn[1] . "," . $arr_conn[2] . "," . $arr_conn[0];
							}

						} else {
							$product_type = "";
						}

						$arr_batchorder_list = array();
						$arr_batchorder_list['goods_id'] = $k;
						$arr_batchorder_list['goods_sku'] = $arr_goods['goods_sku'];
						$arr_batchorder_list['batchorder_id'] = $order_id;
						$arr_batchorder_list['product_type'] = $product_type;
						$arr_batchorder_list['product_num'] = $v['nums']; //数量
						$arr_batchorder_list['createtime'] = $datetime;
						$this->db->insert('db_batchorder_list', $arr_batchorder_list);

					}
				}
			}
		}
		//外部开发
		if($post['made_factory']==7) {
					$datetime = date("Y-m-d H:i:s");
					//更新 db_batchorder
					$arr_batchorder = array();
					$arr_batchorder['goods_code'] = $db_goods['goods_parent_sku'];
					$arr_batchorder['goods_name'] = $db_goods['goods_name'];
					$arr_batchorder['price'] = $db_goods['wages']; //使用工价
					//工厂预期交货日期
					$timestamp = $post['daysum']*86400+ strtotime($post['opertime']);
					$arr_batchorder['goods_date'] = date("Y-m-d",$timestamp); //客户期望交货日期
					$arr_batchorder['status'] = 4; //新订单
					if ($post['cang'] == 1) {
						$arr_batchorder['cang'] = "1号仓"; //发往仓库
					}
					if ($post['cang'] == 2) {
						$arr_batchorder['cang'] = "2号仓"; //发往仓库
					}
					$arr_batchorder['createtime'] = $datetime;
					$arr_batchorder['userid'] = $_COOKIE['userid'];
					$arr_batchorder['create_user'] = $_COOKIE['username'];
					$arr_batchorder['factory_id'] = $post['made_factory']; //外发工厂
					$arr_batchorder['memo'] = $post['memo'];

					$this->db->insert("db_batchorder", $arr_batchorder);
					$order_id = $this->db->insert_id();

					//更新 采购编号
					$this->db->update('db_purchase_list', array('tb_ordersn' => $order_id), " id=" . $pid);

					//更新 db_batchorder_list
					foreach ($arr_unique as $k => $v) {
						$arr_goods = $this->fun->getdatabasesdetail('db_goods', " AND goods_id = '" . $k . "'");
						$rgoodstype = $this->db->get_one("SELECT GROUP_CONCAT(attr_value ORDER BY attr_id ASC)  AS sta FROM `db_goods_attr` WHERE `goods_id` = '" . $k . "'");
						$arr_conn = explode(",", $rgoodstype['sta']);
						if (!empty($arr_conn[1])) {
							if (mb_substr($arr_conn[0], 0, 1) == "男" || mb_substr($arr_conn[0], 0, 1) == "女") {
								$product_type = $arr_conn[1] . "," . $arr_conn[2] . "," . mb_substr($arr_conn[0], 0, 1);
							} else {
								$product_type = $arr_conn[1] . "," . $arr_conn[2] . "," . $arr_conn[0];
							}

						} else {
							$product_type = "";
						}
						$arr_batchorder_list = array();
						$arr_batchorder_list['goods_id'] = $k;
						$arr_batchorder_list['goods_sku'] = $arr_goods['goods_sku'];
						$arr_batchorder_list['batchorder_id'] = $order_id;
						$arr_batchorder_list['product_type'] = $product_type;
						$arr_batchorder_list['product_num'] = $v['nums']; //数量
						$arr_batchorder_list['createtime'] = $datetime;
						$this->db->insert('db_batchorder_list', $arr_batchorder_list);

					}
		}

		 //写记录 
			if($newpid>0)
            $ztcontent = "修改采购单";
			else
			$ztcontent = "添加采购单";
            $this->upstatus_list($pid,21,$ztcontent);
		
           
           
		 if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
		 return $pid;
		
	}
	function getNo()
    {
		//return "B".date("Ymdhis")."";
		$row_purchase_list = $this->fun->getdatabasesdetail('db_purchase_list', "","MAX(id) as id ");
		return $row_purchase_list["id"]+1;
    }
	function upstatus_list($uid,$zt,$ztcontent){
		  //更新记录
		$sqls  =" insert into db_purchase_status set s_sid = '".$uid."',s_zt ='$zt',s_zt_content='$ztcontent',s_updatetime='".date("Y-m-d H:i:s")."', s_admins = '".$_COOKIE['username']."'";
		return $this->db->query($sqls);
	}

	/******输入SKU获取信息*********/
	function getStockSInfo($val)
	{
		if(!$val)
		{
			return false;
		}
		$where= "goods_sku like '%".$val."%'";
		$where.=" or goods_name like '%".$val."%'";
		$where.=" or en_goods_name like '%".$val."%'";
		$where.=" or goods_parent_sku like '%".$val."%'";
		$res = $this->db->select('goods_id,goods_sku,goods_name,g_costprice')->limit(20)->get_where("db_goods",$where)->result_array();
		if(count($res)>0)
		{
			foreach($res as $key=>$r)
			{
				//库存信息
				$storage = $this->db->get_where('db_goods_stock', " goods_id = '" . $r["goods_id"] . "'")->result_array();
                $res[$key]["storage"] = $storage;
				//默认合理的采购价
				$res[$key]['g_costprice'] = $this->fun->get_Goods_costprice($r['goods_sku']);


				//采购信息
				$bus = $this->fun->getdatabasesdetail('db_goods_purchasing', "  And goods_id = '" . $r["goods_id"] . "'");
				$res[$key]["businessman"] = $bus['businessman'];
				$res[$key]["businessmanline"] = $bus['businessmanline'];

				//图片信息
				$goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $r["goods_id"])->result_array();
                $thumb_url = $goods_images[0]["thumb_url"];
                if ($thumb_url) {
                    $res[$key]["imagesurl"] = $thumb_url;
                }elseif ($goods_images[0]['local_url']) {
                    $res[$key]["imagesurl"] = "/".$goods_images[0]['local_url'];
                }elseif ($goods_images[0]['images_url']) {
                    $res[$key]["imagesurl"] = "/".$goods_images[0]['imagesurl'];
                } else {
                   $res[$key]["imagesurl"] = "/fuman/images/s-l500.jpg";
                }
				
				//唯一标识
				$skucode = $this->getskucode(4);
				$res[$key]['skucode'] = $skucode;
			}
			return $res;
		}
	}

	function saveslistget($uid,$st)
	{
		
		if($st == 1)
		{
			$detail = $this->fun->getdatabasesdetail('db_purchase_list'," AND id='{$uid}'");
			if($detail['tb_ordersn']=='')
			{
				return 201;
			}

			//添加日志信息
			$msg = "状态由：请求付款,更改为：等待付款";
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			//$arr_logs['pid'] = "";
			$arr_logs['goods_code'] = $detail['orderstockid'];
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $detail['id'];
			$this->db->insert('db_externalbuy_log', $arr_logs);

		}

		if($st=='Y')	//完成支付，需要记录在途数和在途时间
		{
			$st = 2;
			$detail = $this->fun->getdatabasesdetail('db_purchase_list'," AND id='{$uid}'");
			$waitday = strtotime($detail['opertime'])+intval($detail['daysum'])* 86400;	//预计到达时间
			$goodslist = $this->getBuyListvice($uid);
			foreach($goodslist as $key=>$rs)
			{
				$resstock = $this->fun->getdatabasesdetail('db_goods_stock', " AND goods_id = '" . $rs['goods_id']. "' AND storage_id='".$detail['cang']."'");
				if($resstock){
					 $sqlup = "update db_goods_stock set in_transit =in_transit+$rs[nums],waitday='".$waitday."',waitnum='".$rs['pid']."' where goods_id = '$rs[goods_id]' AND storage_id = '".$detail['cang']."'";
					 $this->db->query($sqlup);
				}else{
					$post="";
					$cangname = $this->fun->getdatabasesdetail('db_storage'," AND id='".$detail['cang']."'");
					$post['goods_id'] = $rs['goods_id'];
					$post['storage_id'] = $detail['cang'];
					$post['storage_name'] = $cangname['storagename'];
					$post['stock'] = 0;
					$post['in_transit']  = $rs['nums'];
					$post['positions'] = null;
					$post['waitnum'] = $rs['pid'];
					$post['waitday'] = $waitday;
					$this->db->insert('db_goods_stock',$post);
				}
			}

			//添加日志信息
			$msg = "状态由：等待付款,更改为：已支付";
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			//$arr_logs['pid'] = "";
			$arr_logs['goods_code'] = $detail['orderstockid'];
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $detail['id'];
			$this->db->insert('db_externalbuy_log', $arr_logs);
			
		}
		if($st=='N'){
			
			$this->upstatus_list($uid,24,'取消支付');
			$sql =" update db_purchase_list set ps = '1',pstime='".date("Y-m-d H:i:s")."'  where id='$uid'";  
			$this->db->query($sql);
			//取消支付需要将在途回滚
			$detail = $this->fun->getdatabasesdetail('db_purchase_list'," AND id='{$uid}'");
			$goodslist = $this->getBuyListvice($uid);
			foreach($goodslist as $key=>$rs)
			{
				 $sqlup = "update db_goods_stock set in_transit =in_transit-$rs[nums],waitday='',waitnum='' where goods_id = '$rs[goods_id]' AND storage_id = '".$detail['cang']."'";
				 $this->db->query($sqlup);
			}

			//添加日志信息
			$msg = "状态由：已支付,更改为：取消支付(等待付款)";
			$arr_logs['createtime'] = date("Y-m-d H:i:s");
			//$arr_logs['pid'] = "";
			$arr_logs['goods_code'] = $detail['orderstockid'];
			$arr_logs['details'] = $msg;
			$arr_logs['username'] = $_COOKIE['username'];
			$arr_logs['userid'] = $_COOKIE['userid'];
			$arr_logs['purchase_id'] = $detail['id'];
			$this->db->insert('db_externalbuy_log', $arr_logs);

			 return;
		}


	    $sql =" update db_purchase_list set ps = '".$st."',pstime='".date("Y-m-d H:i:s")."'  where id='$uid'";  
        $this->db->query($sql);
		
		if($st==1){
			$this->upstatus_list($uid,22,'请求付款操作');
		}
		if($st==2){
			$this->upstatus_list($uid,23,'支付完成');
		}
    }
	
	/***获取采购单基本信息********/
	function getBuyListByUid($id ,$where="")
	{
		$detail = $this->db->get_where('db_purchase_list',"id='{$id}' $where")->result_array();
		if(count($detail)==0)
		 {
			die('没有数据');
		}
		$detail  = $detail[0];
		$detail['tb_ordersnst'] = nl2br($detail['tb_ordersn']);
		
		if(strstr($detail["tb_kd"],"tborder"))
		{
			$tb_kds = unserialize($detail['tb_kd']);
			$detail['tborder'] = $tb_kds['tborder'];
			$detail['kdname'] = $tb_kds['kdname'];
			$detail['kdnumber'] = $tb_kds['kdnumber'];
			$detail['types1'] = 1;
		}else{
			$detail['tborder'] = $detail['tb_ordersn'];
			$detail['kdname'] = $detail['kdname'];
			$detail['kdnumber'] = $detail['tb_kd'];
			$detail['types1'] = 2;
		}


		
		$storagelist = $this->fun->getdatabasesdetail('db_storage', ' and id = '.$detail['cang']);//仓库信息
		$detail['storagename'] = $storagelist['storagename'];

		return $detail;
	}

	//从库存预警提交过来的信息
	function getProducePurchase($goods_id,$goods_num)
	{
		$goods_id =trim($goods_id,",");
		$goods_num =trim($goods_num,",");
	
		$detail_list = array();
		
		$goods_id = explode(",",$goods_id);
		$goods_num = explode(",",$goods_num);
		
		if(count($goods_id)==0)
		{
			die("错误！");
		}
		foreach($goods_id as $key=>$r)
		{
			$goods = $this->fun->getdatabasesdetail("db_goods"," AND goods_id = '".$r."'");
			$detail_list[$key]['good_name']= $goods['goods_name'];
			$detail_list[$key]['good_no']= $goods['goods_sku'];
			
			$detail_list[$key]['dailysales']= $goods['dailysales'];
			$detail_list[$key]['sales1']= $goods['sales1'];
			$detail_list[$key]['sales2']= $goods['sales2'];
			$detail_list[$key]['sales3']= $goods['sales3'];

			$detail_list[$key]['goods_id']= $goods['goods_id'];
			$bus = $this->fun->getdatabasesdetail('db_goods_purchasing', "  And goods_id = '" . $r . "'");
			if(!$bus)
			{
				//查看父目录有没有
				$bus = $this->fun->getdatabasesdetail('db_goods_parent', "  And p_parent_id = '" . $goods['goods_parentID'] . "'");
			}
			$detail_list[$key]['buyer']= $bus['businessman'];
			$detail_list[$key]["businessman"] = $bus['businessman'];
			$detail_list[$key]["businessmanline"] = $bus['businessmanline'];
			$detail_list[$key]['price']=$goods['g_costprice'];
			$detail_list[$key]['nums']= $goods_num[$key];
			$detail_list[$key]['qualityinNum']= 0;
			$detail_list[$key]['total']=$goods_num[$key]*$goods['g_costprice'];
			//自动生成一个随机码
			$skucode = $this->getskucode(4);
			$detail_list[$key]['skucode']= $skucode;

			$storage = $this->fun->getdatabaseslist("db_goods_stock A LEFT JOIN db_storage B on A.storage_id=B.id"," AND B.is_show=1 and A.goods_id='".$r."'","A.*");
			$detail_list[$key]["storage"] = $storage;

			//采购信息
			
			

			//图片信息
			$goods_images = $this->fun->getdatabasesdetail('db_goods_images', "  And goods_id = '" . $r . "'");
			$thumb_url = $goods_images["thumb_url"];
			if ($thumb_url) {
				$detail_list[$key]["imagesurl"] = $thumb_url;
			}elseif ($goods_images['local_url']) {
				$detail_list[$key]["imagesurl"] = "/".$goods_images['local_url'];
			} else {
			   $detail_list[$key]["imagesurl"] = "/fuman/images/s-l500.jpg";
			}
		}
		return $detail_list;
		
	}
	function getskucode($nums=5)
	{
		$code = $this->fun->randCode($nums,1);
		$rsdb = $this->fun->getdatabasesdetail("db_purchase_vice"," AND skucode = '".$code."'");
		if($rsdb)
		{
			return $this->getskucode(5);
		}else{
			return $code;	
		}
	}
	/***获取采购单商品信息********/
	function getBuyListvice($id)
	{
		$detail_list = $this->db->get_where('db_purchase_vice',"pid='{$id}'")->result_array();
		foreach($detail_list as $key=>$r)
		 {
			
			$storage = $this->fun->getdatabaseslist("db_goods_stock A LEFT JOIN db_storage B on A.storage_id=B.id"," AND B.is_show=1 and A.goods_id='".$r['goods_id']."'","A.*");
			foreach($storage as $keycag=>$cangs)
			{
				$sendgoodsnum = $this->pm->getsendthegoods($r['goods_id'],$cangs['storage_id']);
				$storage[$keycag]["sendgoodsnum"] = $sendgoodsnum;
			}
			//待发货数
			$detail_list[$key]["storage"] = $storage;
			
			//采购信息
			$bus = $this->fun->getdatabasesdetail('db_goods_purchasing', "  And goods_id = '" . $r["goods_id"] . "'");
			$detail_list[$key]["businessman"] = $bus['businessman'];
			$detail_list[$key]["businessmanline"] = $bus['businessmanline'];

			//图片信息
			$goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $r["goods_id"])->result_array();
			$thumb_url = $goods_images[0]["thumb_url"];
			if ($thumb_url) {
				$detail_list[$key]["imagesurl"] = $thumb_url;
			}elseif ($goods_images[0]['local_url']) {
				$detail_list[$key]["imagesurl"] = "/".$goods_images[0]['local_url'];
			}elseif ($goods_images[0]['images_url']) {
				$detail_list[$key]["imagesurl"] = "/".$goods_images[0]['imagesurl'];
			} else {
			   $detail_list[$key]["imagesurl"] = "/fuman/images/s-l500.jpg";
			}
		}
		
		return $detail_list;
	}

	function savefullnewadd($id)
	{
		//标识为已入库
		 $this->db->trans_begin();
		$sql = "update db_purchase_list set rkflag=1,rkuser='".$_COOKIE['username']."',rktime ='".date("Y-m-d H:i:s")."' where id='$id' ";
        $this->db->query($sql);
		
		$detail = $this->getBuyListByUid($id);
		$this->upstatus_list($detail['id'],26,'入库完成');
		//获取采购单信息
		$detail_list = $this->getBuyListvice($detail['id']);
		foreach($detail_list as $key=>$rs)
		{
			$good_no = $rs["good_no"];
			$goods_id = $rs["goods_id"];
			$qualityinNum = $rs["qualityinNum"];
			$nums = $rs["nums"];
			$storage_id = $detail["cang"];
			$daysum     = $detail["daysum"];
			$opertime   = $detail["opertime"];
			$pid = $detail["id"];
			//入库、记录日志、去掉在途
			if($qualityinNum)
			{
				$bus = $this->fun->getdatabasesdetail('db_goods_stock', "  And goods_id = '" . $goods_id . "' AND storage_id = '".$storage_id."'");
				$in_transit = $bus['in_transit'] - $nums;
				if($in_transit<0)
				{
					$in_transit = 0;
				}
				if($rs['waitnum'] == $pid)
				{
					$waitnum = 0;
				}else{
					$waitnum = $rs['waitnum'];
				}
				 $sqlup = "update db_goods_stock set stock = stock+$qualityinNum,in_transit ='".$in_transit."',waitday='',waitnum='".$waitnum."' where goods_id = '$goods_id' AND storage_id = '".$storage_id."'";
				 $this->db->query($sqlup);

				 //存日志
				 $new_data = $bus["stock"]+$qualityinNum;
				 $content = "采购单<a href='/purchase/ordermod/$pid/show' target=_thank> $detail[orderstockid]</a>入库操作 原来库存[$bus[stock]] 现在库存[ $new_data ]";
				 $this->fun->goods_stock_log($pid,$goods_id,0,$content,$qualityinNum,1,$bus["stock"],$new_data);    //库存日志
				 $this->fun->goods_update_log($goods_id, $content, 1,$bus["stock"],$new_data);    //日志
			}
		}
		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }

		return true;
	}
	function getcang($good_no)
	{
		if($good_no)
			{
				$notwowarehousepositions = $this->config->item('notwowarehousepositions');
				if($notwowarehousepositions) 
				{
					$notwowarehousepositions = explode("|",$notwowarehousepositions);
					$expgood_no = implode("','",$good_no);
					$res = $this->fun->getdatabaseslist("db_goods_stock A LEFT JOIN db_goods B on A.goods_id = B.goods_id"," AND  goods_sku in('".$expgood_no."') and storage_id = 1","positions");
					if($res)
					{
						foreach($res as $key=>$rd){
							if($rd["positions"]){
								$rdpositions = explode(".",$rd["positions"]);
								if(in_array($rdpositions[0],$notwowarehousepositions))
								{
									$cang = 2;
									return $cang;
								}
								
							}
						}
					}
				}
				
			}
	}
}
